﻿using System;
using System.Linq;
using System.Threading.Tasks;
using MassTransit;
using MassTransit.Courier;
using MassTransit.Courier.Contracts;
using MassTransitDemo.Shared;

namespace MassTransitDemo.RequestService
{
    class Program
    {
        static async Task Main()
        {
            var busControl = CreateBus();
            await busControl.StartAsync();

            var validateQueueName = "rabbitmq://119.3.138.127:5672/execute_validate";
            var retrieveQueueName = "rabbitmq://119.3.138.127:5672/execute_retrieve";
            var validateAddress = new Uri(validateQueueName);
            var retrieveAddress = new Uri(retrieveQueueName);

            try
            {
                while (true)
                {
                    string value = await Task.Run(() =>
                    {
                        Console.WriteLine("Enter message (or quit to exit)");
                        Console.Write("> ");
                        return Console.ReadLine();
                    });

                    if ("quit".Equals(value, StringComparison.OrdinalIgnoreCase))
                        break;

                    var tasks = Enumerable.Range(0, 3).Select(x => Task.Run(async () =>
                    {
                        var builder = new RoutingSlipBuilder(NewId.NextGuid());

                        builder.AddActivity("Validate", validateAddress);
                        builder.AddActivity("Retrieve", retrieveAddress);

                        builder.SetVariables(new
                        {
                            RequestId = NewId.NextGuid(),
                            Address = x,
                        });

                        RoutingSlip routingSlip = builder.Build();

                        await busControl.Publish<IRoutingSlipCreated>(new
                        {
                            TrackingNumber = routingSlip.TrackingNumber,
                            Timestamp = routingSlip.CreateTimestamp,
                        });

                        await busControl.Execute(routingSlip);
                    }));

                    Task.WaitAll(tasks.ToArray());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception!!! OMG!!! {0}", ex);
                Console.ReadLine();
            }
            finally
            {
                await busControl.StopAsync();
            }
        }

        static IBusControl CreateBus()
        {
            var rabbitMQAddress = "119.3.138.127";
            return Bus.Factory.CreateUsingRabbitMq(x => x.Host(rabbitMQAddress, 5672, "masstransitdemo", h =>
            {
                h.Username("masstransitdemo");
                h.Password("masstransitdemo@test");
            }));
        }
    }
}
